#include "stdafx.h"
#include "Server.h"

using namespace Network;

int _tmain(int argc, _TCHAR* argv[])
{
	//Starts the server
	WSADATA wsaData;
	fprintf(stdout, "Welcome to the server\n");
	
	//Start Winsock
	int wsResult = WSAStartup(MAKEWORD(2,2), &wsaData);
	if (wsResult != 0) {
		fprintf(stdout, "WSAStartup failed with error: %d\n", wsResult);	
		WSACleanup();
		return -1;
	}

	//Create listeners on different ports
	INET_Addr alarmAddress = INET_Addr(LISTENING_IF, ALARM_PORT);
	INET_Addr logAddress = INET_Addr(LISTENING_IF, LOG_PORT);
	INET_Addr patientAddress = INET_Addr(LISTENING_IF, PATIENT_PORT);

	//Create EventHandlers
	AlarmEventHandler* alarmEvent = new AlarmEventHandler(alarmAddress);
	LoggingEventHandler* logEvent = new LoggingEventHandler(logAddress);
	PatientEventHandler* patientEvent = new PatientEventHandler(patientAddress);

	//Create the multiplexer
	EventDemultiplex* multiplex = new EventDemultiplex();
	SelectReactor* reactor = new SelectReactor(multiplex);

	//Register the valid event-handlers.
	reactor->register_handler((EventHandler*)alarmEvent);
	reactor->register_handler((EventHandler*)logEvent);
	reactor->register_handler((EventHandler*)patientEvent);

	// Event loop that processes client connection requests and log records reactively
	while ( true )
	{
		reactor->handle_events();
	}

	//Clean up winsock
	WSACleanup();
	return 0;
}

